﻿
using Furion.DataEncryption.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq.Expressions;

namespace RedPacket.Services.Proxy
{
    /// <summary>
    /// 代理商接口
    /// </summary>
    [Authorize, ApiDescriptionSettings("代理商")]
    public class ProxyServices : BaseServices
    {
        private readonly ISqlSugarClient db;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="db"></param>
        /// <param name="zjStore"></param>
        public ProxyServices(ISqlSugarClient db)
        {
            this.db = db;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="fmt"></param>
        /// <returns></returns>
        public async Task<object> GetChart(string fmt)
        {
            string fmtInfo = "%Y-%m-%d";

            string showInfo = "%Y-%m-%d";

            if (fmt == "month")
            {
                fmtInfo = "%Y-%m";

                showInfo = "%m";
            }

            if (fmt == "day")
            {
                fmtInfo = "%Y-%m-%d";

                showInfo = "%d";
            }

            if (fmt == "year")
            {
                fmtInfo = "%Y";

                showInfo = "%Y";
            }

            string sql = $@"select 
                        sum(storePrice) as price , DATE_FORMAT(created,'{showInfo}') as time
                        from `order` 
                        where PayStatus = 1 and ProxyId = {PROXYID}
                        GROUP BY DATE_FORMAT(created,'{fmtInfo}')";

            var data = await db.SqlQueryable<dynamic>(sql).ToListAsync();

            return Ok(data);
        }

        /// <summary>
        /// 资金记录
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public async Task<object> GetMoneyLog(int type)
        {
            var data = await db.Queryable<Entity.ProxyMoneyLog>()

                .Where(x => x.UID == PROXYID)

                .OrderBy(x => x.Id, OrderByType.Desc)

                .ToPagedListAsync(PageNo, PageSize);

            return Ok(data);
        }

        /// <summary>
        /// 设置商户状态
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<object> SetStoreState(int id)
        {
            var store = await db.Queryable<Entity.Store>()

                .FirstAsync(x => x.Id == id && x.ProxyId == PROXYID);

            if (store == null) return No("商户不存在");

            if (store.State is 0 or 2) return No("商户还在审核中");

            if (store.State == 1) store.State = 3;

            if (store.State == 3) store.State = 1;

            bool state = await db.Updateable(store).ExecuteCommandHasChangeAsync();

            return Msg(state);
        }

        /// <summary>
        /// 获取商户的所有流水
        /// </summary>
        /// <param name="id"></param>
        /// <param name="payType">订单类型 全部传入-1</param>
        /// <returns></returns>
        public async Task<object> GetStoreOrder(int id, int payType)
        {
            var order = await db.Queryable<Entity.Order>()

                .WhereIF(id > 0, x => x.StoreId == id)

                .Where(x => x.PayStatus == Entity.PayStatus.已支付 && x.ProxyId == PROXYID)

                .WhereIF(payType > -1, $"orderType = {payType}")

                .Includes(x => x.Client)

                .Includes(x => x.Store)

                .OrderBy(x => x.Id, OrderByType.Desc)

                .ToPagedListAsync(PageNo, PageSize);

            return Ok(order);
        }

        /// <summary>
        /// 商户流水统计
        /// </summary>
        /// <param name="id"></param>
        /// <param name="payType">支付类型 全部传入-1</param>
        /// <returns></returns>
        public async Task<object> GetStoreOrderCount(int id, int payType)
        {
            var now = DateTime.Now;

            string storeWhere = id > 0 ? $" and storeid = {id}" : "";

            string payTypeWhere = payType > -1 ? $" and OrderType = {payType} " : "";

            string day7sql = $@" SELECT count(0) as count,sum(payprice) as price FROM `order` where 1=1 {storeWhere} {payTypeWhere} and created > '{now.AddDays(-7).ToString("yyyy-MM-dd")}' and PayStatus = 1 and proxyId = {PROXYID}";

            string day30sql = $@" SELECT count(0) as count,sum(payprice) as price FROM `order` where 1=1 {storeWhere} {payTypeWhere} and created > '{now.AddDays(-30).ToString("yyyy-MM-dd")}' and PayStatus = 1 and proxyId = {PROXYID}";

            string day90sql = $@" SELECT count(0) as count,sum(payprice) as price FROM `order` where 1=1 {storeWhere} {payTypeWhere} and created > '{now.AddDays(-90).ToString("yyyy-MM-dd")}' and PayStatus = 1 and proxyId = {PROXYID}";

            var day7 = await db.SqlQueryable<dynamic>(day7sql).FirstAsync();

            var day30 = await db.SqlQueryable<dynamic>(day7sql).FirstAsync();

            var day90 = await db.SqlQueryable<dynamic>(day7sql).FirstAsync();

            return Ok(new { day7, day30, day90 });
        }

        /// <summary>
        /// 商户流水统计
        /// </summary>
        /// <param name="id"></param>
        /// <param name="payType">支付类型 全部传入-1</param>
        /// <returns></returns>
        public async Task<object> GetStoreOrderSum(int id, int payType)
        {
            var now = DateTime.Now;

            Expression<Func<Entity.Order, bool>> globalFilter = x => x.ProxyId == PROXYID && x.PayStatus == Entity.PayStatus.已支付;

            var day7 = await db.Queryable<Entity.Order>()
                .WhereIF(payType > -1, x => x.PayType == (Entity.PayType)payType)
                .WhereIF(id > 0, x => x.StoreId == id)
                .Where(globalFilter).Where("YEARWEEK(created) = YEARWEEK(CURDATE())")
                .Select<dynamic>("count(0) num ,sum(payPrice) price").FirstAsync();

            var day30 = await db.Queryable<Entity.Order>()
               .WhereIF(payType > -1, x => x.PayType == (Entity.PayType)payType)
               .WhereIF(id > 0, x => x.StoreId == id)
               .Where(globalFilter).Where(x => x.Created.ToString("yyyyMM") == DateTime.Now.ToString("yyyyMM"))
               .Select<dynamic>("count(0) num ,sum(payPrice) price").FirstAsync();

            var day90 = await db.Queryable<Entity.Order>()
               .WhereIF(payType > -1, x => x.PayType == (Entity.PayType)payType)
               .WhereIF(id > 0, x => x.StoreId == id)
               .Where(globalFilter).Where(x => x.Created.ToString("yyyy") == DateTime.Now.ToString("yyyy"))
               .Select<dynamic>("count(0) num ,sum(payPrice) price").FirstAsync();



            return Ok(new { day7, day30, day90 });
        }

    }
}
